﻿using Shake.Business.Infrastructures;
using Shake.Domain.Filters;
using Shake.Framework.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Shake.Framework.Mvc;
using Shake.Framework.View;
using Shake.Domain.Models;
using Shake.Framework.Attributes;
using Shake.Domain.Dto;

namespace Shake.Web.Controllers
{
    [Theme]
    public class DepartmentController : Controller
    {
        public IDepartmentService DepartmentService { get; set; }
        //
        // GET: /Department/
        public ActionResult Index(DepartmentFilter filter, PageArgument page)
        {
            if (Request.IsAjaxRequest())
            {
                var results = DepartmentService.GetDepartments(filter, page);
                return Json(results);
            }
            else
            {
                var results = DepartmentService.GetAllDepartment(filter);
                return this.Shake(results);
            }
        }

        public ActionResult All(DepartmentFilter filter)
        {
            var results = DepartmentService.GetAllDepartment(filter);
            return Json(results);
        }

        public ActionResult AllJsonP(DepartmentFilter filter)
        {
            var results = DepartmentService.GetAllDepartment(filter);
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(results);
            Response.ContentType = "application/x-javascript; charset=utf-8";
            return Content(string.Format("callback({0})", json));
        }

        public ActionResult Create(List<Department> department)
        {
            DepartmentService.Create(department);
            return Json(department);
        }

        public ActionResult Remove(List<Department> department)
        {
            DepartmentService.Remove(department);
            return Json(department);
        }

        public ActionResult Update(List<Department> department)
        {
            DepartmentService.Update(department);
            return Json(department);
        }

        public ActionResult Group()
        {
            var departments = DepartmentService.GetAllDepartment(new DepartmentFilter());
            var departmentDtos = departments.Select(t => new DepartmentDto
            {
                expanded = true,
                id = t.Id,
                pid = t.ParentId,
                text = t.Name,
                items = new List<DepartmentDto>()
            }).ToList();

            for (int i = 0; i < departmentDtos.Count; i++)
            {
                var departmentDto = departmentDtos[i];
                departmentDto.items = departmentDtos.Where(t => t.pid == departmentDto.id).ToList();
            }
            return this.ToJson(departmentDtos.Where(t => t.pid == null).ToList());
        }
    }
}